package com.study.gateway_service.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: LWM
 * @date: 2019/2/27
 * @time: 10:18
 * Description: No Description
 */
@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 设置为什么拦截类型 前置拦截 后置拦截
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器执行顺序,order值越小,越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 4;
    }

    /**
     * 做判断逻辑 返回false不拦截 返回true拦截
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //System.out.println(request.getRequestURI()); /gateway/order/api/v1/order/save
        //System.out.println(request.getRequestURL()); http://localhost:9000/gateway/order/api/v1/order/save
        //匹配这个路径就拦截
        if("/gateway/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){
            return true;
        }
        return false;
    }

    /**
     * 编写业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        /**判断有没有token*/
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            //有可能存在于参数中
            token = request.getParameter("token");
        }
        /**验证登录逻辑 可以使用JWT*/
        if(StringUtils.isBlank(token)){
            //如果没有token 则返回401
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }
        return null;
    }
}
